/*
 * @Date: 2023-08-16 10:29:00
 */
import { isEmptyObject, isObject, isArray } from "./is/base";

/**
 * @description: kkweb 网络请求验签规则
 * @param {object} 网络请求参数对象
 * @return {*} 按照指定规则排序后的字符串
 * @example
 * ```js
 * encryption({username: 'kukewang', password: '123456'})
 * => password=123456&username=kukewang
 * ```
 */

export const encryption = (obj: Record<string, unknown> = {}): string => {
  if (isEmptyObject(obj)) {
    return "";
  }

  // 根据key排序
  const keyArr = Object.keys(obj);
  // 按照key生序排列
  keyArr.sort();
  const newObj = <any>{};

  for (let i = 0; i < keyArr.length; i++) {
    if (_isNotEmpty_(obj[keyArr[i]])) {
      newObj[keyArr[i]] = obj[keyArr[i]];
    }
  }

  const newArr = Object.keys(newObj);
  let str = "";

  for (let j = 0; j < newArr.length; j++) {
    const value = newObj[newArr[j]];
    if (isObject(value) || isArray(value) || _isEmptyStr_(value)) {
      continue;
    }

    str += `${newArr[j]}=${value}&`;
  }

  if (str.endsWith("&")) {
    return str.substring(0, str.length - 1);
  }

  return str;
};

const _isNotEmpty_ = (str: any): boolean => {
  if (typeof str === "number") {
    return true;
  }

  if (typeof str === "undefined") {
    return true;
  }

  if (
    (typeof str === "string" && str.trim() === "") ||
    (Array.prototype.isPrototypeOf(str) && str.length === 0) ||
    (Object.prototype.isPrototypeOf(str) && Object.keys(str).length === 0)
  ) {
    return false;
  }

  return true;
};

const _isEmptyStr_ = (str: any): boolean => {
  if (typeof str === "number") {
    return false;
  }

  return str === "" || str === null || str === undefined;
};
